package com.asset.salesforce.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.asset.salesforce.converter.CallConverter;
import com.asset.salesforce.domain.Call;
import com.asset.salesforce.domain.Contact;
import com.asset.salesforce.domain.Employee;
import com.asset.salesforce.domain.Post;
import com.asset.salesforce.domain.UpdateChatter;
import com.asset.salesforce.enums.FOLLOWTYPE;
import com.asset.salesforce.enums.UPDATETYPE;
import com.asset.salesforce.form.CallForm;
import com.asset.salesforce.service.CalendarService;
import com.asset.salesforce.service.CallService;
import com.asset.salesforce.service.CheckingUtilsService;
import com.asset.salesforce.service.CompanyService;
import com.asset.salesforce.service.ContactService;
import com.asset.salesforce.service.EmployeeService;
import com.asset.salesforce.service.JoinRequestService;
import com.asset.salesforce.service.PostService;
import com.asset.salesforce.service.UpdateChatterService;

@Controller
public class CallController {

	@Autowired
	private CallService callService;
	@Autowired
	private JoinRequestService joinRequestService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private ContactService contactService;
	@Autowired
	private CalendarService calendarService;
	
	@Autowired
	private CheckingUtilsService checkingUtilsService;
	@Autowired
	private PostService postService;
	@Autowired
	private UpdateChatterService updateChatterService;
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/new-call",method=RequestMethod.GET)
	public String newCall(Model model,HttpSession session,HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) {
		if (SecurityUtils.getSubject().hasRole("callAdd")){
		Employee userDetails=(Employee)session.getAttribute("userDetails");
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:/s/login.html";
		}
		Integer parentId = Integer.parseInt(request.getParameter("parentId").toString());
		String parentType =request.getParameter("parentType").toString();
		//Integer parentType = 1;
		//Integer parentId =Integer.parseInt(request.getParameter("id").toString());
		System.out.println("##################################bbbb " + parentId + "#########" + parentType );
		List<Contact> contacts = contactService.getContactByParent(parentType, parentId);
		String companyName = userDetails.getCompany().getCompanyName();
		List<Employee> crmStaff = companyService.getActivatedEmployeesByCompanyName(companyName);

		System.out.println("=========================bbbb " + contacts.size() );

		if(crmStaff != null){
			for (Employee employee : crmStaff) {
				employee.setIsFollowed(checkingUtilsService.checkIfCurrentFollowThatPeople(userDetails, employee));
//				if(!employee.getIsOwner()){
//					if(!employee.getIsActive()){
//						companyEmployees.remove(employee);
//					}
//				}
			}
		}
		if(contacts == null){
			contacts = (List<Contact>) new Contact();
		}
		CallForm callForm = new CallForm();
		
		model.addAttribute("crmStaff", crmStaff);
		model.addAttribute("contacts", contacts);
		model.addAttribute("callForm", callForm);
		model.addAttribute("parentId", parentId);
		model.addAttribute("parentType", parentType);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "new-call";
		}
		else{
			return "accessDenied";
		}
	}
	
	

	@RequestMapping(value="/new-call",method=RequestMethod.POST)
	public String newActionPost(Model model,HttpSession session,HttpServletRequest request,
			@Valid CallForm callForm,BindingResult result
			) {
	//	System.out.println("=========================================="+callForm.getEndTime());
		String startTime = callForm.getStartTime();
		String endTime = callForm.getEndTime();
		if(startTime!=null&&!(startTime.equalsIgnoreCase(""))){
			if(endTime!=null&&!(endTime.equalsIgnoreCase(""))){
				String[] TargetStartTimeForTime = startTime.split(":");
                Integer targetStartTime1 = (Integer.parseInt(TargetStartTimeForTime[0])*60)+Integer.parseInt(TargetStartTimeForTime[1]);
                
                String[] targetEndTimeForTime = endTime.split(":");
                Integer targetEndTime1 = (Integer.parseInt(targetEndTimeForTime[0])*60)+Integer.parseInt(targetEndTimeForTime[1]);
                Integer timeBetwwenThem = targetEndTime1-targetStartTime1;
				if(timeBetwwenThem<5){
		            result.rejectValue("startTime", "startTime","Please,Enter at leat 5 Minutes");
				}
			}
		}
		
		if (result.hasErrors()) {
			Employee userDetails=(Employee)session.getAttribute("userDetails");
			if(null ==session.getAttribute("userDetails") ){
				return "redirect:/s/login.html";
			}
			Integer parentId = Integer.parseInt(request.getParameter("parentId").toString());
			String parentType =request.getParameter("parentType").toString();
			//Integer parentType = 1;
			//Integer parentId =Integer.parseInt(request.getParameter("id").toString());
			System.out.println("##################################bbbb " + parentId + "#########" + parentType );
			List<Contact> contacts = contactService.getContactByParent(parentType, parentId);
			String companyName = userDetails.getCompany().getCompanyName();
			List<Employee> crmStaff = companyService.getActivatedEmployeesByCompanyName(companyName);

			System.out.println("=========================bbbb " + contacts.size() );

			if(crmStaff != null){
				for (Employee employee : crmStaff) {
					employee.setIsFollowed(checkingUtilsService.checkIfCurrentFollowThatPeople(userDetails, employee));
//					if(!employee.getIsOwner()){
//						if(!employee.getIsActive()){
//							companyEmployees.remove(employee);
//						}
//					}
				}
			}
//			if(contacts == null){
//				contacts = (List<Contact>) new Contact();
//			}
//			CallForm callForm2 = new CallForm();
			
			model.addAttribute("crmStaff", crmStaff);
			model.addAttribute("contacts", contacts);
			
			model.addAttribute("parentId", parentId);
			model.addAttribute("parentType", parentType);
			
			joinRequestService.getJoinRquestNo(session, model);
			calendarService.getAppointmentEventsNo(session, model);
			calendarService.getCallEventssNo(session, model);
			
			return "new-call";
		}
		Employee userDetails=(Employee)session.getAttribute("userDetails");
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:/s/login.html";
		}
		Call call = new Call();
		DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
		format.setLenient(false);
		Date newDate;
		if(callForm.getCrmStaff() != null){
			call.setCrmStaff(employeeService.getById(callForm.getCrmStaff()));
		}
		if(callForm.getContactedPerson() != null){
			call.setContactedPerson(contactService.getContactById(callForm.getContactedPerson()));
		}
		if(callForm.getDate() != null){
			try {
				newDate = format.parse(callForm.getDate());
//				newDate = callForm.getDate();
				call.setDate(newDate);
			} catch (ParseException e) {
//				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		//added by hisham
		if(callForm.getStartTime()!=null){
			call.setStartTime(callForm.getStartTime());
		}
		if(callForm.getEndTime()!=null){
			call.setEndTime(callForm.getEndTime());
		}
		//end
		if(callForm.getInOutCall() != null){
			call.setInOutCall(Boolean.valueOf(callForm.getInOutCall()));
		}
		if(callForm.getDecisionMaker() != null){
			call.setDecisionMaker(Boolean.valueOf(callForm.getDecisionMaker()));
		}
		if(callForm.getComment() != null){
			call.setComment(callForm.getComment());
		}
		if(callForm.getNextFollowUp() != null){
			call.setNextFollowUp(Boolean.valueOf(callForm.getNextFollowUp()));
		}
		if(callForm.getNextFollowUpType() != null){
			call.setFollowUpType(callForm.getNextFollowUpType());
		}
		if(callForm.getNextFollowUpDate() != null&&!(callForm.getNextFollowUpDate().equalsIgnoreCase(""))){
			try {
				newDate = format.parse(callForm.getNextFollowUpDate());
				call.setFollowUpDate(newDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}
		if(callForm.getNextFollowUpDetails() != null){
			call.setFollowUpDetails(callForm.getNextFollowUpDetails());
		}
			
			
			
		call.setParentId(callForm.getParentId());
		call.setParentType("lead");
		Date date = new Date();
		call.setDateCreated(date);
		call.setDateModified(date);
		callService.addCall(call);
		calendarService.callEvent(call);
		UpdateChatter updateChatter = new UpdateChatter();
		updateChatter.setAction_emp(userDetails);
		updateChatter.setDate(new Date());
		updateChatter.setFollowedId(call.getId());
		updateChatter.setFollowType(FOLLOWTYPE.Call.getType());
		updateChatter.setUpdateType(UPDATETYPE.Added.getName());
		Post post = new Post();
		post.setPostDate(new Date());
		post.setPoster(userDetails);

		String postText = "<a href='/sales/s/view-call.html?id="+call.getId()+"'>i created Call at Time:"+call.getStartTime()+ "And Date"+callForm.getDate()+"</a>";
		post.setPostText(postText);
		postService.addPost(post);	
		updateChatter.setPost(post);
		updateChatterService.add(updateChatter);
		model.addAttribute("userDetails", userDetails);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "redirect:/s/calendar?empId="+userDetails.getId();
	}
	
	@RequestMapping(value="/edit-call",method=RequestMethod.GET)
	public String editCall(Model model,HttpSession session,HttpServletRequest request, ModelMap modelMap) {
		if (SecurityUtils.getSubject().hasRole("callEdit")){
		Employee userDetails=(Employee)session.getAttribute("userDetails");
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:/s/login.html";
		}

		Integer parentId = Integer.parseInt(request.getParameter("parentId").toString());
		String parentType =request.getParameter("parentType").toString();
		Call call =callService.getCallnById(new Call(),Integer.parseInt(request.getParameter("id"))); 
		CallConverter callConverter = new CallConverter();
		CallForm callForm = callConverter.ConvertCall(call);
		if(callForm.getDate() != null){
			String date = callForm.getDate().substring(0, 10);
			System.out.println("date is"+date);
			
		}
		
		//Integer parentId = 1;
		String companyName = userDetails.getCompany().getCompanyName();
		List<Employee> crmStaff = companyService.getActivatedEmployeesByCompanyName(companyName);
		List<Contact> contacts = contactService.getContactByParent(parentType, parentId);

		if(crmStaff != null){
			for (Employee employee : crmStaff) {
				employee.setIsFollowed(checkingUtilsService.checkIfCurrentFollowThatPeople(userDetails, employee));
			}
		}
		if(contacts == null){
			contacts =  new ArrayList<Contact>();
		}
		
		model.addAttribute("id",request.getParameter("id"));
		model.addAttribute("parentId",request.getParameter("parentId"));
		model.addAttribute("parentType",request.getParameter("parentType"));
		model.addAttribute("crmStaff", crmStaff);
		System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"+contacts.size());
		model.addAttribute("contacts", contacts);
		model.addAttribute("callForm", callForm);
		//model.addAttribute("parentId", parentId);
		model.addAttribute("userDetails", userDetails);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "edit-call";
		}
		else{
			return "accessDenied";
		}
	}

	@RequestMapping(value="/edit-call",method=RequestMethod.POST)
	public String editcall(Model model,HttpSession session,HttpServletRequest request,
			/*@RequestParam(value="crmStaff",required =false) Integer crmStaff,
			@RequestParam(value="contactedPerson",required =false) Integer contactedPerson,
			@RequestParam(value="date", required=false) String date,
			@RequestParam(value="inOutCall", required=false) Boolean inOutCall,
			@RequestParam(value="decisionMaker", required=false) Boolean decisionMaker,
			@RequestParam(value="comment", required=false) String comment,
			@RequestParam(value="nextFollowUp", required=false) Boolean nextFollowUp,
			@RequestParam(value="nextFollowUpType", required=false) String nextFollowUpType,
			@RequestParam(value="nextFollowUpDate", required=false) String nextFollowUpDate,
			@RequestParam(value="nextFollowUpDetails", required=false) String nextFollowUpDetails,
			@RequestParam(value="id", required=false) Integer id,
			@RequestParam(value="parentId", required=false) Integer parentId,
			@RequestParam(value="parentType", required=false) String parentType*/
			@Valid @ModelAttribute("callForm") CallForm callForm,BindingResult result
			) {
		Employee userDetails=(Employee)session.getAttribute("userDetails");
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:/s/login.html";
		}
		String startTime = callForm.getStartTime();
		String endTime = callForm.getEndTime();
		if(startTime!=null&&!(startTime.equalsIgnoreCase(""))){
			if(endTime!=null&&!(endTime.equalsIgnoreCase(""))){
				String[] TargetStartTimeForTime = startTime.split(":");
                Integer targetStartTime1 = (Integer.parseInt(TargetStartTimeForTime[0])*60)+Integer.parseInt(TargetStartTimeForTime[1]);
                
                String[] targetEndTimeForTime = endTime.split(":");
                Integer targetEndTime1 = (Integer.parseInt(targetEndTimeForTime[0])*60)+Integer.parseInt(targetEndTimeForTime[1]);
                Integer timeBetwwenThem = targetEndTime1-targetStartTime1;
				if(timeBetwwenThem<5){
		            result.rejectValue("startTime", "startTime","Please,Enter at leat 5 Minutes");
				}
			}
		}
		if (result.hasErrors()) {
			Integer parentId = Integer.parseInt(request.getParameter("parentId").toString());
			String parentType =request.getParameter("parentType").toString();
			System.out.println("##################################bbbb " + parentId + "#########" + parentType );
			List<Contact> contacts = contactService.getContactByParent(parentType, parentId);
			String companyName = userDetails.getCompany().getCompanyName();
			List<Employee> crmStaff = companyService.getActivatedEmployeesByCompanyName(companyName);
			System.out.println("=========================bbbb " + contacts.size() );
			if(crmStaff != null){
				for (Employee employee : crmStaff) {
					employee.setIsFollowed(checkingUtilsService.checkIfCurrentFollowThatPeople(userDetails, employee));
//					if(!employee.getIsOwner()){
//						if(!employee.getIsActive()){
//							companyEmployees.remove(employee);
//						}
//					}
				}
			}
//			if(contacts == null){
//				contacts = (List<Contact>) new Contact();
//			}
//			CallForm callForm2 = new CallForm();	
			model.addAttribute("id",request.getParameter("id"));
			model.addAttribute("crmStaff", crmStaff);
			model.addAttribute("contacts", contacts);
			model.addAttribute("parentId", parentId);
			model.addAttribute("parentType", parentType);		
			joinRequestService.getJoinRquestNo(session, model);
			calendarService.getAppointmentEventsNo(session, model);
			calendarService.getCallEventssNo(session, model);
			return "edit-call";
		}
		
		Call call = callService.getCallnById(new Call(),Integer.parseInt(request.getParameter("id")));
		DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
		Date newDate;
		if(callForm.getCrmStaff() != null){
			call.setCrmStaff(employeeService.getById(callForm.getCrmStaff()));
		}
		if(callForm.getContactedPerson() != null){
			call.setContactedPerson(contactService.getContactById(callForm.getContactedPerson()));
		}
		if(callForm.getDate() != null){
			try {
				newDate = format.parse(callForm.getDate());
				call.setDate(newDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		if(callForm.getInOutCall() != null){
			call.setInOutCall(Boolean.valueOf(callForm.getInOutCall()));
		}
		if(callForm.getDecisionMaker() != null){
			call.setDecisionMaker(Boolean.valueOf(callForm.getDecisionMaker()));
		}
		if(callForm.getComment() != null){
			call.setComment(callForm.getComment());
		}
		if(callForm.getNextFollowUp() != null){
			call.setNextFollowUp(Boolean.valueOf(callForm.getNextFollowUp()));
		}
		if(callForm.getNextFollowUpType() != null){
			call.setFollowUpType(callForm.getNextFollowUpType());
		}
		if(callForm.getNextFollowUpDate() != null){
			try {
				newDate = format.parse(callForm.getNextFollowUpDate());
				call.setFollowUpDate(newDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}
		if(callForm.getNextFollowUpDetails() != null){
			call.setFollowUpDetails(callForm.getNextFollowUpDetails());
		}
		if(callForm.getParentId()!=null){
			call.setParentId(callForm.getParentId());
		}

			UpdateChatter updateChatter = new UpdateChatter();
			updateChatter.setAction_emp(userDetails);
			updateChatter.setDate(new Date());
			updateChatter.setFollowedId(call.getId());
			updateChatter.setFollowType(FOLLOWTYPE.Call.getType());
			updateChatter.setUpdateType(UPDATETYPE.Edited.getName());
			Post post = new Post();
			post.setPostDate(new Date());
			post.setPoster(userDetails);

			String postText = "<a href='/sales/s/view-call.html?id="+call.getId()+"'>i edited Call at Time:"+call.getStartTime()+ "And Date"+callForm.getDate()+"</a>";
			post.setPostText(postText);
			postService.addPost(post);	
			updateChatter.setPost(post);
			updateChatterService.add(updateChatter);
			
		call.setParentType(request.getParameter("parentType"));
		call.setParentType("lead");
		call.setDateModified(new Date());
		callService.saveOrUpdate(call);
		calendarService.callEvent(call);
		model.addAttribute("userDetails", userDetails);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "redirect:/s/viewLead.html?id="+call.getParentId();
	}

	@RequestMapping(value="/view-call",method=RequestMethod.GET)
	public String viewCall(Model model,HttpSession session,HttpServletRequest request, ModelMap modelMap) {
		if (SecurityUtils.getSubject().hasRole("callView")){
		Employee userDetails=(Employee)session.getAttribute("userDetails");
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:/s/login.html";
		}
		Call call =callService.getCallnById(new Call(),Integer.parseInt(request.getParameter("id"))); 
		
		//Integer parentId = 1;
		model.addAttribute("id",request.getParameter("id"));
		model.addAttribute("parentId",request.getParameter("parentId"));
		model.addAttribute("parentType",request.getParameter("parentType"));
		model.addAttribute("call", call);
		//model.addAttribute("parentId", parentId);
		model.addAttribute("userDetails", userDetails);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "view-call";
		}else{
			return "accessDenied";
		}
	}

	
}
